package org.vsg.common.pagination.web.taglibs;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vsg.common.pagination.AdvancedPagination;
import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.wrapper.AdvancedGenericWebSortByPaginationWrapper;

/**
 * JSP Tag Handler class
 *
 * @jsp.tag   name = "FirstGrouping"
 *            display-name = "Name for FirstGrouping"
 *            description = "Description for FirstGrouping"
 *            body-content = "JSP"
 */
public class FirstGroupingTag extends TagSupport {

	final static Logger logger = LoggerFactory.getLogger(FirstGroupingTag.class);	
	
	public FirstGroupingTag() {
		// TODO Auto-generated constructor stub
	}
	
	public int doStartTag() throws JspException {
		PaginationBarTag parent = (PaginationBarTag)this.findAncestorWithClass(this,PaginationBarTag.class);
		
		if (parent == null) {
			throw new JspException("Element \"firstGrouping\" must set in the element \"paginationBar\"! ");
		}
		
		Pagination page = parent.getPagination();
		
		if (!(page instanceof AdvancedPagination)) {
			logger.warn("The Advanced Pagination is not supported!");
		}
		
		AdvancedPagination apage = (AdvancedPagination)page;
		if (apage.getTotalGrouping() > 0  && apage.getGroupingIndex() > apage.getFirstGrouping()) {
			pageContext.setAttribute("isFirstGroupingAvailable", new Boolean(true));
		} else {
			pageContext.setAttribute("isFirstGroupingAvailable", new Boolean(false));
		}		
		
		// get the parent pagination
		Object wrapper = pageContext.getAttribute(parent.getId());
		
		if (wrapper instanceof AdvancedGenericWebSortByPaginationWrapper) {
			AdvancedGenericWebSortByPaginationWrapper webWrapper = (AdvancedGenericWebSortByPaginationWrapper)wrapper;
			pageContext.setAttribute("firstGroupingUrl",webWrapper.getFristGroupingUrl());
		}

		return Tag.EVAL_BODY_INCLUDE;
	}

}
